package com.cyan.app.workflow.activity.WHM;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.activity.Wap.WebView1Activity;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.ItnbrLabBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.PullDownView;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
//import java.util.logging.Handler;

/**
 * 品号查询定位
 * Created by DXW on 2016-08-08.
 */
public class ItnbrsActivity  extends BaseActivity implements PullDownView.OnPullDownListener, AdapterView.OnItemClickListener{
    private Button mButtonSearch;
    private Button mButtonItnbr; //品号
    private EditText mEditTextItnbr;
    private EditText mEditTextItdsc;
    public static final String ITNBR = "itnbrs_itnbr";
    public static final String TAG = "ItnbrsActivity";
    private List<ItnbrLabBean.ItnbrBean> mItnbrBeans;
    private ItnbrsAdapter adapter;
    private ListView prossinfo_lv;
    private PullDownView mPullDownView;
    private Boolean isPressMore = false;
    private int pageCount = 8;
    /** 请求第几页数据 */
    private int intPageNo = 1;
    /** 是否有下一页 */
    private boolean nextPage = false;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private List<ItnbrLabBean.ItnbrBean> mItnbrDatas = new ArrayList<ItnbrLabBean.ItnbrBean>();
    private int selectedIndex=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whm_itnbrs);
        titleBar();

        mPullDownView = (PullDownView) findViewById(R.id.whm_itnbrs_lv);
        mPullDownView.setOnPullDownListener(this);
        prossinfo_lv = mPullDownView.getListView();
        prossinfo_lv.setOnItemClickListener(this);
        // 隐藏并且禁用头部刷新
        mPullDownView.setHideHeader();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0004 && resultCode == RESULT_OK){
            mItnbrBeans.remove(selectedIndex);
            mItnbrDatas.remove(selectedIndex);
            adapter.notifyDataSetChanged();
        }
        if(requestCode == 0x0001 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                if(result.indexOf("30020")==0){
                    mEditTextItnbr.setText(String.valueOf(result.substring(5)));
                }else {
                    AsyncLoaderManno task = new AsyncLoaderManno();
                    task.execute("208", result);
                }
           }
        }
    }
    public class AsyncLoaderManno extends AsyncTask<String,Integer,String>
    {
        @Override
        protected void onPreExecute() {
            showdialog.showDialog(ItnbrsActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Manno", params[1]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            try {
                // CommonBean commonBean = new Gson().fromJson(s, CommonBean.class);
                JSONObject json = new JSONObject(s);
                if (!json.getString("Code").equals("1")) {
                    AppUtils.showTip(ItnbrsActivity.this, json.getString("Msg"));
                } else {
                    String result = json.getString("Result");
                    JSONObject json1 = new JSONObject(result);
                    mEditTextItnbr.setText(json1.getString("itnbrf"));
                }
            }catch (Exception e){

            }
            showdialog.closeDialog();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        //adapter.notifyDataSetChanged();
    }

    private void titleBar() {
        TextView mTextView =(TextView)findViewById(R.id.top_title_info);
        mTextView.setText("品号列表");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        Button  mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setVisibility(View.VISIBLE);
        mButton.setText("查询");
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog();
            }
        });
    }

    private void showAlertDialog() {
        LayoutInflater inflater = this.getLayoutInflater();
        final View layout = inflater.inflate(R.layout.whm_itnbrs_search, (ViewGroup) findViewById(R.id.whm_itnbrs_seach_layout));
        final Dialog alertDialog= new AlertDialog.Builder(this).setCancelable(false).setView(layout).create();
        final TextView mTextView =(TextView)layout.findViewById(R.id.top_title_info);
        mTextView.setText("查询条件");
        final Button back = (Button) layout.findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                alertDialog.hide();
            }
        });
        //品名
        mEditTextItnbr=(EditText)layout.findViewById(R.id.whm_itnbrs_seach_itnbr);
        String itnbr = PreferenceManager.getDefaultSharedPreferences(this).getString(ITNBR, null);
        if(itnbr!=null){
            mEditTextItnbr.setText(String.valueOf(itnbr));
        }
        mButtonItnbr = (Button)layout.findViewById(R.id.whm_itnbrs_seach_itnbr_saoma);
        mButtonItnbr.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(ItnbrsActivity.this, CaptureActivity.class), 0x0001);
            }
        });

        //图号
        mEditTextItdsc = (EditText)layout.findViewById(R.id.whm_itnbrs_seach_itdsc);
        //确定
        final Button mButtonSubmit=(Button)layout.findViewById(R.id.whm_itnbrs_seach_submit);
        mButtonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEditTextItnbr.getText().toString().isEmpty()&&mEditTextItdsc.getText().toString().isEmpty()) {
                    AppUtils.showTip(ItnbrsActivity.this, "请输入查询条件");
                }else {
                    mItnbrDatas.clear();
                    AsyncLoader task = new AsyncLoader();
                    task.execute("321"
                            , mEditTextItnbr.getText().toString()
                            , mEditTextItdsc.getText().toString()
                            );
                    alertDialog.hide();
                }
            }
        });
        alertDialog.show();
    }
    public class AsyncLoader extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showdialog.showDialog(ItnbrsActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Itnbr", params[1]);
                param.put("Itdsc", params[2]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            ItnbrLabBean commonBean = new Gson().fromJson(s, ItnbrLabBean.class);
            if (commonBean.getCode() < 1) {
                AppUtils.showTip(ItnbrsActivity.this, commonBean.getMsg());
            } else {
                mItnbrBeans = commonBean.getResult();
                startProssThread();
            }
            showdialog.closeDialog();
        }
    }
    private void getData(int PageNo){
        if(mItnbrBeans==null) return;
        int count = (intPageNo*pageCount)> mItnbrBeans.size()?mItnbrBeans.size():intPageNo*pageCount;
        for(int i = (intPageNo-1)* pageCount;i< count;i++){
            mItnbrDatas.add(mItnbrBeans.get(i));
        }
    }
    private void  showList(){
        // 获取更多数据之外的请求，如首次请求数据，
        if (!isPressMore) {
            getData(intPageNo);
            adapter = new ItnbrsAdapter(ItnbrsActivity.this);
            prossinfo_lv.setAdapter(adapter);
        }else {
            // 获取更多数据
            getData(intPageNo);
            adapter.notifyDataSetChanged();
        }
        // 判断是否有下一页
        if (mItnbrBeans.size() > mItnbrDatas.size()) {
            // 显示并启用自动获取更多
            mPullDownView.setShowFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(true, 1);
        } else {
            // 隐藏 并禁用尾部
            mPullDownView.setHideFooter();
            // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
            mPullDownView.enableAutoFetchMore(false, 1);
        }
        // 告诉它获取更多完毕 这个事线程安全的 可看源代码
        mPullDownView.notifyDidMore();

        isPressMore = false;
    }
    /**
     * listview单项点击事件
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.putExtra("Type", "301");
        intent.putExtra("Code", mItnbrDatas.get(position - 1).getItnbr());
        intent.setClass(ItnbrsActivity.this, WebView1Activity.class);
        startActivity(intent);
    }

    /**
     * listview刷新
     */
    public void onRefresh() {

    }
    /**
     * listview更多
     */
    public void onMore() {
        isPressMore = true;
        // 发送更多请求
        intPageNo++;
        startProssThread();
    }
    // 启动线程
    private void startProssThread() {
        showList();
    }
    public class ItnbrsAdapter extends BaseAdapter {
        private LayoutInflater inflater = null;
        public ItnbrsAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mItnbrDatas.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            holder = new ViewHolder();
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_VERTICAL;
            convertView = inflater.inflate(R.layout.whm_itnbrs_list, null);
            holder.itnbrs_itnbr = (TextView) convertView.findViewById(R.id.whm_itnbrs_list_itnbr);
            holder.itnbrs_itdsc = (TextView) convertView.findViewById(R.id.whm_itnbrs_list_itdsc);
            holder.itnbrs_itcls = (TextView) convertView.findViewById(R.id.whm_itnbrs_list_itcls);
            holder.itnbrs_unmsr1 = (TextView) convertView.findViewById(R.id.whm_itnbrs_list_unmsr1);
            holder.itnbrs_detail = (ImageView) convertView.findViewById(R.id.whm_itnbrs_list_detail);

            holder.itnbrs_itnbr.setText(mItnbrDatas.get(position).getItnbr());
            holder.itnbrs_itdsc.setText(mItnbrDatas.get(position).getItdsc());

            if(!mItnbrDatas.get(position).getUnmsr2().isEmpty()){
                holder.itnbrs_unmsr1.setText(mItnbrDatas.get(position).getUnmsr1()+ "\n" + mItnbrDatas.get(position).getUnmsr2());
            }else {
                holder.itnbrs_unmsr1.setText(mItnbrDatas.get(position).getUnmsr1());
            }
            holder.itnbrs_detail.setImageResource(R.drawable.right);
            holder.itnbrs_itcls.setText(mItnbrDatas.get(position).getItcls());
            convertView.setTag(holder);
            return convertView;
        }

        class ViewHolder {
            TextView itnbrs_itnbr;
            TextView itnbrs_itdsc;
            TextView itnbrs_itcls;
            TextView itnbrs_unmsr1;
            ImageView itnbrs_detail;
        }
    }
}


